package com.qf.springbootshiro.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.springbootshiro.user.entity.Pers;
import com.qf.springbootshiro.user.entity.Role;
import com.qf.springbootshiro.user.entity.User;
import com.qf.springbootshiro.user.dao.UserDao;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.springbootshiro.user.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XvYingHai
 * @since 2022-10-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Autowired
    private UserDao userDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void regist(User user) {
        String salt = UUID.randomUUID().toString().substring(5, 13);
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());
        user.setSalt(salt);
        this.save(user);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<String> getPermission(User user) {
        return userDao.getPermissionsByUser(user)
                .stream()
                .map(Pers::getUrl)
                .collect(Collectors.toList());

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<String> getRole(User user) {
        return userDao.getRoleByUser(user)
                .stream()
                .map(Role::getName)
                .collect(Collectors.toList());
    }
}
